package com.sxfq.loansupermarket.backsystem.modular.system.controller;

import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.node.MenuNode;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.UserMapper;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.User;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroUser;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.system.dao.MenuDao;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 登录控制器
 *
 * @author fengshuonan
 * @Date 2017年1月10日 下午8:25:24
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    MenuDao menuDao;

    @Autowired
    UserMapper userMapper;

    @Autowired
    private SqlMapper sqlMapper;

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        //获取菜单列表
        List<Integer> roleList = ShiroKit.getUser().getRoleList();
        if (roleList == null || roleList.size() == 0) {
            ShiroKit.getSubject().logout();
            model.addAttribute("tips", "该用户没有角色，无法登陆");
            return "/login.html";
        }
        List<MenuNode> menus = menuDao.getMenusByRoleIds(roleList);
        List<MenuNode> titles = MenuNode.buildTitle(menus);
        model.addAttribute("titles", titles);
        //获取用户头像
        Integer id = ShiroKit.getUser().getId();
        User user = userMapper.selectById(id);
        String avatar = user.getAvatar();
        model.addAttribute("avatar", avatar);
        model.addAttribute("outpatientName", ShiroKit.getSessionAttr("outpatientName"));
        model.addAttribute("userName", user.getAccount());
        model.addAttribute("passWord", ShiroKit.getSessionAttr("password"));
        return "/index.html";
    }

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String to_index(Model model) {
        String sql = " select t1.simplename from user t left join dept t1 on t.deptid=t1.id " +
                "where t.account='" + ShiroKit.getSessionAttr("username") + "'";
        Dept dept = sqlMapper.selectOne(sql, Dept.class);
        if (dept != null) {
            if (!"总公司".equals(dept.getSimplename())) {
                if (!(ShiroKit.getSessionAttr("outpatientName")).equals(dept.getSimplename())) {
                    model.addAttribute("tips", "该用户没有权限登陆该诊所");
                    model.addAttribute("username", ShiroKit.getSessionAttr("username"));
                    model.addAttribute("password", ShiroKit.getSessionAttr("password"));
                    model.addAttribute("outpatientName", ShiroKit.getSessionAttr("outpatientName"));
                    return "/login.html";
                }
            }
        } else {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        //获取菜单列表
        List<Integer> roleList = ShiroKit.getUser().getRoleList();
        if (roleList == null || roleList.size() == 0) {
            ShiroKit.getSubject().logout();
            model.addAttribute("tips", "该用户没有角色，无法登陆");
            return "/login.html";
        }
        List<MenuNode> menus = menuDao.getMenusByRoleIds(roleList);
        List<MenuNode> titles = MenuNode.buildTitle(menus);
        model.addAttribute("titles", titles);
        //获取用户头像
        Integer id = ShiroKit.getUser().getId();
        User user = userMapper.selectById(id);
        String avatar = user.getAvatar();
        String sql1 = " select t.abbreviation from dept t where t.simplename= '" + ShiroKit.getSessionAttr("outpatientName") + "'";
        Dept dept1 = sqlMapper.selectOne(sql1, Dept.class);
        ShiroKit.getUser().setAbbreviation(dept1.getAbbreviation());
        ShiroKit.getUser().setOutpatientName(ShiroKit.getSessionAttr("outpatientName"));
        model.addAttribute("avatar", avatar);
        model.addAttribute("tips", "登录成功");
        model.addAttribute("abbreviation", dept1.getAbbreviation());
        model.addAttribute("outpatientName", ShiroKit.getSessionAttr("outpatientName"));
        model.addAttribute("userName", user.getAccount());
        model.addAttribute("passWord", ShiroKit.getSessionAttr("password"));
        return "/index.html";
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        model.addAttribute("username", ShiroKit.getSessionAttr("username"));
        model.addAttribute("password", ShiroKit.getSessionAttr("password"));
        model.addAttribute("outpatientName", ShiroKit.getSessionAttr("outpatientName"));
        return "/login.html";
    }

    /**
     * 点击登录执行的动作
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginVali(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        String username = super.getPara("username").trim();
        String password = super.getPara("password").trim();
        String outpatientName = super.getPara("outpatientName").trim();

//        //验证验证码是否正确
//        if(ToolUtil.getKaptchaOnOff()){
//            String kaptcha = super.getPara("kaptcha").trim();
//            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//            if(ToolUtil.isEmpty(kaptcha) || !kaptcha.equals(code)){
//                throw new InvalidKaptchaException();
//            }
//        }

        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
        token.setRememberMe(true);

        currentUser.login(token);

        ShiroUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());

        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), HttpKit.getIp()));
        ShiroKit.getSession().setAttribute("sessionFlag", true);
        ShiroKit.setSessionAttr("outpatientName", outpatientName);
        ShiroKit.setSessionAttr("username", username);
        ShiroKit.setSessionAttr("password", password);
        return REDIRECT + "/";
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logOut() {
        ShiroUser ss = ShiroKit.getUser();
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
        ShiroKit.getSubject().logout();
        return REDIRECT + "/login";
    }
}
